package com.huicoo.forestmanager.ui.patrol.PatrolRecordDetailsActivity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.huicoo.forestmanager.R;
import com.huicoo.forestmanager.base.BaseActivity;
import com.huicoo.forestmanager.network.HttpService;
import com.huicoo.forestmanager.network.bean.patrol.RecordDetailsIssuesListBean;
import com.huicoo.forestmanager.network.bean.patrol.RecorddetailsBean;
import com.huicoo.forestmanager.network.bean.patrol.RecordlistBean;
import com.huicoo.forestmanager.others.WebRefreshEvent;
import com.huicoo.forestmanager.ui.patrol.forestCampTask.NeedVerifyProblemContainerFragment;
import com.huicoo.forestmanager.util.JsonUtils;
import com.huicoo.forestmanager.util.LogUtils;
import com.huicoo.forestmanager.util.MulchUtil;
import com.huicoo.forestmanager.widget.LoadingDialog;
import com.tianditu.android.maps.GeoPoint;
import com.tianditu.android.maps.MapController;
import com.tianditu.android.maps.MapView;
import com.tianditu.android.maps.MyLocationOverlay;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.tianditu.android.maps.MapView.TMapType.MAP_TYPE_IMG;
import static com.tianditu.android.maps.MapView.TMapType.MAP_TYPE_VEC;

/**
 * 巡查记录详情
 */
public class PatrolRecordDetailsActivity extends BaseActivity {

    @BindView(R.id.map_view)
    MapView map_view;

    @BindView(R.id.positioning)
    ImageView positioning;

    @BindView(R.id.subtract)
    ImageView subtract;

    @BindView(R.id.add)
    ImageView add;

    @BindView(R.id.back)
    ImageView back;

    @BindView(R.id.view_pager)
    ViewPager view_pager;

    @BindView(R.id.tab_Layout)
    TabLayout tab_Layout;


    @BindView(R.id.map_type_iv)
    ImageView map_type_iv;

    @BindView(R.id.map_type_tv)
    TextView map_type_tv;

    @BindView(R.id.turn_back)
    ImageView turn_back;

    @BindView(R.id.issues_list)
    TextView issues_list;


    private MapController mMapController;
    private MyLocationOverlay myLocationOverlay;
    private LoadingDialog loadingDialog;

    private RecordlistBean.Data mData;
    private NeedVerifyProblemContainerFragment mInstance;
    private List<RecorddetailsBean.Data.Coordinates> mCoordinates;

    public static void start(Activity activity, RecordlistBean.Data data) {
        Intent intent = new
                Intent(activity, PatrolRecordDetailsActivity.class);
        //在Intent对象当中添加一个键值对
        intent.putExtra("data", data);
        activity.startActivity(intent);

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_patrol_record_details;
    }

    @Override
    protected void initView() {
        //初始化地图设置
        initMapView();

        //初始化数据
        initData();

        EventBus.getDefault().register(this);
    }


    //初始化地图设置
    private void initMapView() {
        //设置启用内置的缩放控件
        map_view.setBuiltInZoomControls(false);

        //得到mMapView的控制权,可以用它控制和驱动平移和缩放
        mMapController = map_view.getController();

        //创建MyLocationOverlay
        myLocationOverlay = new MyLocationOverlay(this, map_view);

        //启用指南针位置更新
        myLocationOverlay.enableCompass();

        //启用我的位置
        myLocationOverlay.enableMyLocation();

        map_view.addOverlay(myLocationOverlay);

        //设置地图zoom级别
        mMapController.setZoom(15);

        //矢量
        map_view.setMapType(MAP_TYPE_VEC);

        //定位到当前位置
//        locateCurrentLocation();
    }

    //定位到当前位置
    private void locateCurrentLocation() {
        //获得当前位置
        GeoPoint myLocation = myLocationOverlay.getMyLocation();

        //设置地图中心点
        mMapController.setCenter(myLocation);

        //动画移动到当前位置
        mMapController.animateTo(myLocation);
    }

    //初始化数据
    private void initData() {
        Intent intent = this.getIntent();
        mData = (RecordlistBean.Data) intent.getSerializableExtra("data");
        //获取数据
        getData();
    }

    //获取数据
    private void getData() {

        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(this);
            loadingDialog.show();
        }
        Call<RecorddetailsBean> call = HttpService.getInstance().getrecorddetails(mData.getID());
        call.enqueue(new Callback<RecorddetailsBean>() {
            @Override
            public void onResponse(Call<RecorddetailsBean> call, Response<RecorddetailsBean> response) {
                RecorddetailsBean body = response.body();
                //数据请求成功
                LogUtils.e("巡查详情" + JsonUtils.toJson(response.body()));
                if (body == null) return;
                if (response.body() != null && TextUtils.equals(response.body().getCode(), "200")) {
                    mCoordinates = body.getData().getCoordinates();

                    //绘制轨迹
                    MulchUtil.drawTheRangerTrajectory(map_view, body.getData().getCoordinates());

                    //初始化ViewPager
                    initViewPager(body);

                    //获取巡查详情问题列表
                    getRecordDetailsIssuesListBean();
                }
                loadingDialog.dismiss();
            }

            @Override
            public void onFailure(Call<RecorddetailsBean> call, Throwable t) {
                loadingDialog.dismiss();
                LogUtils.v("gogogo detail fail");
                t.printStackTrace();
            }
        });


    }

    //获取巡查详情问题列表
    public void getRecordDetailsIssuesListBean() {
        Call<RecordDetailsIssuesListBean> call2 = HttpService.getInstance().getRecordDetailsIssuesList(mData.getID());
        call2.enqueue(new Callback<RecordDetailsIssuesListBean>() {
            @Override
            public void onResponse(Call<RecordDetailsIssuesListBean> Object, Response<RecordDetailsIssuesListBean> response) {

                //数据请求成功
                LogUtils.e("问题列表：" + JsonUtils.toJson(response.body()));
                if (response.body() != null && TextUtils.equals(response.body().getCode(), "200")) {
                    mInstance.setData(response.body().getData().getRows());
                    String totalNum = String.valueOf(response.body().getData().getTotalNum());
                    String content = String.format("问题列表(%s)", totalNum);
                    SpannableStringBuilder stringBuilder = new SpannableStringBuilder(content);
                    ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#25B3D3"));
                    stringBuilder.setSpan(foregroundColorSpan, 4, 4 + totalNum.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    issues_list.setText(stringBuilder.toString());
                }
            }

            @Override
            public void onFailure(Call<RecordDetailsIssuesListBean> call, Throwable t) {
                //数据请求成功
                LogUtils.e("巡查详情问题列表" + JsonUtils.toJson(t.getMessage()));
            }
        });
    }


    //初始化ViewPager
    private void initViewPager(RecorddetailsBean body) {

        PatrolRecordDetailsAdapter pageAdapter = new PatrolRecordDetailsAdapter(getSupportFragmentManager(), this);

        PatrolRecordBasicInformationFragment fragment = PatrolRecordBasicInformationFragment.getInstance();
        Bundle bundle = new Bundle();
        bundle.putSerializable("data", body.getData());
        fragment.setArguments(bundle);
        pageAdapter.addFragmentPager(fragment);

        mInstance = NeedVerifyProblemContainerFragment.getInstance();
        pageAdapter.addFragmentPager(mInstance);

        view_pager.setAdapter(pageAdapter);//设置适配器
        //设置与视图页关联
        tab_Layout.setupWithViewPager(view_pager);

    }


    @OnClick({R.id.positioning, R.id.subtract, R.id.add, R.id.back, R.id.turn_back, R.id.map_type_ll})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.positioning:
                //定位到当前位置
                locateCurrentLocation();
                break;

            case R.id.subtract:
                // 缩小一级
                mMapController.zoomOut();
                break;

            case R.id.add:
                // 放大一级
                mMapController.zoomIn();
                break;

            case R.id.back:
                this.finish();
                break;

            case R.id.turn_back:

                if (mCoordinates != null && mCoordinates.size() > 0) {
                    //回到轨迹区域中心
                    List<GeoPoint> points = new ArrayList<>();
                    for (int i = 0; i < mCoordinates.size(); i++) {
                        RecorddetailsBean.Data.Coordinates coordinate = mCoordinates.get(i);
                        points.add(new GeoPoint((int) (coordinate.getLatitude() * 1E6), (int) (coordinate.getLongitude() * 1E6)));
                    }
                    MulchUtil.locatePolygonMulchCenter(map_view, points);
                }

                break;

            case R.id.map_type_ll:
                //当前是影像
                if (map_view.getMapType() == MAP_TYPE_IMG) {
                    map_type_iv.setImageResource(R.mipmap.icon_satellite);
                    map_view.setMapType(MAP_TYPE_VEC);
                    map_type_tv.setText("影像");
                } else if (map_view.getMapType() == MAP_TYPE_VEC) {
                    map_type_iv.setImageResource(R.mipmap.icon_plane);
                    //矢量
                    map_view.setMapType(MAP_TYPE_IMG);
                    map_type_tv.setText("平面");
                }
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void webRefreshEvent(WebRefreshEvent event) {
        //刷新巡查详情问题列表
        getRecordDetailsIssuesListBean();
    }
}
